<template>
    <div class="box">
        <!-- 头部搜索模块 -->
        <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :addFun="addDrawerForm"
            :buttonList="buttonList" />
        <!-- 中间表格模块 -->
        <BaseTable :data="mechanicstableData" :columns="mechanicsDataColumns" :tableHeight="tableHeight"
            :pagination="false" :loading="loading"></BaseTable>

        <div class="page">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryAll.startpage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="queryAll.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="queryAll.totalNum"></el-pagination>
        </div>
        <!-- 新增编辑 -->
        <el-drawer :before-close="handleClose" :title="title" :visible.sync="drawerInner" direction="rtl" size="70%">
            <el-form ref="formRef" label-position="top" style="padding: 10px 20px;" size="small" :rules="formRule"
                :model="innerForm">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="组织" prop="companyId">
                            <el-select style="width: 240px;" placeholder="请选择组织" clearable v-model="innerForm.companyId"
                                v-selecttext="innerForm.companyName, companyList, 'companyId'">
                                <el-option v-for="(item, index) in companyList" :key="item.companyId"
                                    :label="item.companyName" :value="item.companyId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="机械类型" prop="equipmentTypeId">
                            <el-select style="width: 240px;" placeholder="请选择机械类型" clearable
                                v-model="innerForm.equipmentTypeId"
                                v-selecttext="innerForm.equipmentTypeName, equipmentList, 'value', 'label'">
                                <el-option v-for="(item, index) in equipmentList" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="协力队" prop="cooperationId">
                            <el-select style="width: 240px;" v-model="innerForm.cooperationId" clearable
                                placeholder="请选择协力队"
                                v-selecttext="innerForm.cooperationName, customerList, 'cooperationId'">
                                <el-option v-for="item in customerList" :key="item.cooperationId"
                                    :label="item.cooperationName" :value="item.cooperationId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="货种" prop="cargoCategoryCode">
                            <el-select style="width: 240px;" filterable multiple remote
                                v-model="innerForm.cargoCategoryCode" clearable placeholder="请选择货种">
                                <el-option v-for="item in cargoList" :key="item.cargoCategoryCode" :label="item.cargoCategoryName"
                                    :value="item.cargoCategoryCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="位置" prop="position">
                            <el-select style="width: 240px;" v-model="innerForm.position" clearable placeholder="请选择位置">
                                <el-option v-for="item in positionList" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="贸别" prop="tradeType">
                            <el-select style="width: 240px;" v-model="innerForm.tradeType" clearable
                                placeholder="请选择贸别">
                                <el-option v-for="item in tradeTypeList" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="起始区域" prop="startRegionCode">
                            <el-select style="width: 240px;" v-model="innerForm.startRegionCode" clearable
                                placeholder="请选择起始区域"
                                v-selecttext="innerForm.startRegionName, regionList, 'dictValue', 'dictLabel'">
                                <el-option v-for="item in regionList" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="终点区域" prop="endRegionCode">
                            <el-select style="width: 240px;" v-model="innerForm.endRegionCode" clearable
                                placeholder="请选择终点区域"
                                v-selecttext="innerForm.endRegionName, regionList, 'dictValue', 'dictLabel'">
                                <el-option v-for="item in regionList" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单位" prop="unitCode">
                            <el-select style="width: 240px;" v-model="innerForm.unitCode" clearable placeholder="请选择单位"
                                v-selecttext="innerForm.unitName, billingList, 'dictValue', 'dictLabel'">
                                <el-option v-for="item in billingList" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="作业过程" prop="processCode">
                            <el-select style="width: 240px;" v-model="innerForm.processCode" clearable
                                placeholder="请选择作业过程" v-selecttext="innerForm.processName, processData, 'processCode'"
                                @change="changeProcess">
                                <el-option v-for="item in processData" :key="item.processCode" :label="item.processName"
                                    :value="item.processCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="子过程" prop="processCodeItem">
                            <el-select style="width: 240px;" v-model="innerForm.processCodeItem" clearable
                                placeholder="请选择子过程"
                                v-selecttext="innerForm.processNameItem, processZiData, 'processCode', 'processName'">
                                <el-option v-for="item in processZiData" :key="item.processCode"
                                    :label="item.processName" :value="item.processCode">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单价" prop="rate">
                            <el-input-number style="width: 240px;" v-model="innerForm.rate" :precision="2" :step="1"
                                :max="999999"></el-input-number>
                        </el-form-item>
                        <!-- <el-form-item label="操作工艺" prop="craftCode">
                            <el-select style="width: 240px;" v-model="innerForm.craftCode" clearable
                                placeholder="请选择操作工艺"
                                v-selecttext="innerForm.craftName, craftList, 'dictValue', 'dictLabel'">
                                <el-option v-for="item in craftList" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue">
                                </el-option>
                            </el-select>
                        </el-form-item> -->
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <!-- <el-form-item label="包装" prop="packing">
                            <el-select style="width: 240px;" v-model="innerForm.packing" clearable placeholder="请选择包装">
                                <el-option v-for="item in packingList" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item> -->
                    </el-col>
                    <el-col :span="8">
                        <!-- <el-form-item label="货物形态" prop="cargoFormCode">
                            <el-select style="width: 240px;" v-model="innerForm.cargoFormCode" clearable
                                placeholder="请选择货物形态"
                                v-selecttext="innerForm.cargoFormName, cargoFormList, 'dictValue', 'dictLabel'">
                                <el-option v-for="item in cargoFormList" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue">
                                </el-option>
                            </el-select>
                        </el-form-item> -->
                    </el-col>
                    <el-col :span="8">
                        <!-- <el-form-item label="变化后形态" prop="changeFormCode">
                            <el-select style="width: 240px;" v-model="innerForm.changeFormCode" clearable
                                placeholder="请选择变化后形态"
                                v-selecttext="innerForm.changeFormName, cargoFormList, 'dictValue', 'dictLabel'">
                                <el-option v-for="item in cargoFormList" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue">
                                </el-option>
                            </el-select>
                        </el-form-item> -->
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        
                    </el-col>
                    <el-col :span="8">
                        <!-- <el-form-item label="是否外租机械" prop="isOutside">
                            <el-radio-group style="width: 240px;" v-model="innerForm.isOutside">
                                <el-radio label="Y">是</el-radio>
                                <el-radio label="N">否</el-radio>
                            </el-radio-group>
                        </el-form-item> -->
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="是否按油价计费" prop="isOil">
                            <el-radio-group style="width: 240px;" v-model="innerForm.isOil">
                                <el-radio label="Y">是</el-radio>
                                <el-radio label="N">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="16">
                        <el-form-item label="备注" prop="remark">
                            <el-input maxlength="500" type="textarea" :autosize="{ minRows: 2, maxRows: 3 }"
                                placeholder="请输入备注且最多500个字" v-model="innerForm.remark" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="demo-drawer__footer">
                <el-button type="primary" @click="submitInner()" size="small" :loading="ineerLoading">
                    {{ ineerLoading? "提交中 ...": "保 存" }}
                </el-button>
                <el-button size="small" @click="drawerInner = false">取消</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/billingSettlementSys/mechanicsRate'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
export default {
  components: {
    BaseTable,
    headerSearch
  },
  data() {
    return {
      menuFlag: false,
      oldOut: {},
      oldInner: {},
      menuData: [],
      ineerLoading: false,
      tableHeight: window.innerHeight - 200,
      // 搜索框显示对象
      selectObject: [
        {
          name: '机械类型',
          type: 'select',
          modelName: 'equipmentTypeId',
          selectLabel: 'label',
          selectValue: 'value',
          selectData: []
        }
      ],
      // 按钮的list
      buttonList: [
        { label: '新建', type: 'primary', icon: 'el-icon-plus', click: () => this.addDrawerForm, permission: 'costDataSubsystem:costCooperation:insert' }
      ],
      equipmentList: [],
      customerList: [],
      companyList: [],
      processData: [],
      processZiData: [],
      cargoList: [],
      billingList: [],
      regionList: [],
      craftList: [],
      cargoFormList: [],
      positionList: [{
        value: 1,
        label: '前沿'
      }, {
        value: 2,
        label: '转运'
      }, {
        value: 3,
        label: '后场'
      }, {
        value: 4,
        label: '熏蒸库'
      }, {
        value: 5,
        label: '待检区'
      }, {
        value: 6,
        label: '辅助'
      }, {
        value: 7,
        label: '零工'
      }],
      tradeTypeList: [
        {
          value: '内贸',
          label: '内贸'
        },
        {
          value: '外贸',
          label: '外贸'
        }
      ],
      packingList: [{
        value: 1,
        label: '散'
      }, {
        value: 2,
        label: '件'
      }],
      title: '',
      mechanicsDataColumns: [ // table表头
        { prop: 'equipmentTypeName', width: 100, label: '机械类型' },
        { prop: 'cargoCategoryName', width: 200, label: '货种' },
        { prop: 'position', width: 100, label: '位置' },
        { prop: 'cooperationName', width: 100, label: '协力队', isShort: true },
        { prop: 'processName', width: 100, label: '作业过程' },
        { prop: 'processNameItem', width: 100, label: '子过程' },
        // { prop: 'craftName', width: 100, label: '操作工艺' },
        // { prop: 'cargoFormName', width: 100, label: '货物形态' },
        // { prop: 'changeFormName', width: 100, label: '变化后形态' },
        { prop: 'startRegionName', width: 100, label: '起始区域' },
        { prop: 'endRegionName', width: 100, label: '终点区域' },
        { prop: 'rate', label: '单价' },
        { prop: 'unitCode', width: 100, label: '单位' },
        { prop: 'remark', label: '备注' },
        {
          label: '操作',
          width: 200,
          align: 'center',
          fixed: 'right',
          render: (h, params) => {
            return h(
              'div',
              {
                calss: 'btnClass'
              },
              [
                h('el-button', {
                  props: {
                    size: 'mini',
                    disabled: params.row.delFlag == '1'
                  },
                  style: {
                    marginRight: '10px'
                  },
                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML: `<span style='color:#0B6CD6;'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>编辑</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleEdit(params.$index, params.row)
                    }
                  }
                }),

                h('el-button', {
                  props: {
                    size: 'mini'
                  },
                  domProps: {
                    innerHTML: `<span style='color:#F75E5E;'><i class='iconfont icon-1-08'></i><span  style='padding-left:5px;'>删除</span></span>`
                  },
                  on: {
                    click: () => {
                      this.handleDelete('1', params.row.id)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      mechanicstableData: [],
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        totalNum: 0,
        equipmentTypeId: ''
      },
      drawerOut: false,
      flagOut: true,
      outForm: {
        portName: '',
        portCode: '',
        logogram: '',
        nationCode: '',
        sortNum: ''
      },
      drawerInner: false,
      innerForm: {
        companyId: '',
        companyName: '',
        equipmentTypeId: '',
        equipmentTypeName: '',
        cooperationId: '',
        cooperationName: '',
        cargoCategoryCode: [],
        cargoCategoryName: [],
        position: '',
        tradeType: '',
        processCode: '',
        processName: '',
        processCodeItem: '',
        processNameItem: '',
        startRegionCode: '',
        startRegionName: '',
        endRegionCode: '',
        endRegionName: '',
        unitCode: '',
        unitName: '',
        rate: '',
        rateType: '1',
        isOil: 'N',
        remark: ''
      },
      formRule: {
        companyId: [
          { required: true, message: '组织不能为空' }
        ],
        equipmentTypeId: [
          { required: true, message: '机械类型不能为空' }
        ],
        cargoCategoryCode: [
          { required: true, message: '货种不能为空' }
        ],
        unitCode: [
          { required: true, message: '单位不能为空' }
        ],
        rate: [
          { required: true, message: '单价不能为空' }
        ]
      }
    }
  },
  activated() {
    this.getEquipmentType()
    this.getlistCustomer()
    this.getComp()
    this.getProcessList()
    this.getListCargo()
    this.getlistBillingUnit()
    this.getRegionData()
    this.getCraftData()
    this.getCargoFormData()
  },
  methods: {
    // 获取设备类型
    getEquipmentType() {
      publicapi.getEquipmentType().then(res => {
        this.equipmentList = res.data.data
        this.selectObject[0].selectData = this.equipmentList
      })
    },
    /**
     * 获取组织
     */
    async getComp() {
      const res = await publicapi.getListComp()
      this.companyList = res.data.data
    },
    // 获取协力队
    getlistCustomer() {
      publicapi.getCooperationDataById().then(res => {
        this.customerList = res.data.data
      })
    },
    /**
         * 获取作业过程
         */
    async getProcessList() {
      const res = await publicapi.getlistProcess({ mainType: '1' })
      this.processData = res.data.data
    },
    // 获取货种
    getListCargo() {
      publicapi.getlistCargoCategory().then(res => {
        this.cargoList = res.data.data
      })
    },
    // 获取计费单位
    getlistBillingUnit() {
      publicapi.getDictData('BILLING_UNIT').then(res => {
        this.billingList = res.data.data.BILLING_UNIT
      })
    },
    // 字典查询所属区域
    async getRegionData() {
      const res = await publicapi.getDictData('REGION')
      this.regionList = res.data.data.REGION
    },
    // 字典查询操作工艺
    async getCraftData() {
      const res = await publicapi.getDictData('CRAFT')
      this.craftList = res.data.data.CRAFT
    },
    // 字典查询货物形态
    async getCargoFormData() {
      const res = await publicapi.getDictData('CARGO_FORM')
      this.cargoFormList = res.data.data.CARGO_FORM
    },
    // 子作业过程
    async changeProcess(val) {
      this.innerForm.processCodeItem = ''
      this.processZiData = []
      const processId = this.processData.filter(item => item.processCode == val)[0].id
      const res = await publicapi.getProcessZiDataById(processId)
      this.processZiData = res.data.data
    },
    // 获取表格数据
    async getData() {
      this.loading = true
      await api.getData(this.queryAll).then(res => {
        if (res.status == '200') {
          this.mechanicstableData = res.data.data.pages
          this.mechanicstableData.map(item => {
            item.position ? item.position = this.positionList.filter(v => v.value == item.position)[0].label : item.position = ''
            item.unitCode ? item.unitCode = this.billingList.filter(v => v.dictValue == item.unitCode)[0].dictLabel : item.unitCode = ''
          })
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.queryAll.totalNum = res.data.data.totalNum
          this.loading = false
        }
      })
    },
    /**
         * 新建
         */
    addDrawerForm() {
      if (this.title == '修改费率') {
        this.$refs['formRef'].resetFields();
      } else {
        this.innerForm = this.$options.data().innerForm
      }
      this.$nextTick(() => {
        if (!this.drawerInner) {
          this.drawerInner = true
        }
        this.title = '新建费率'
      })
    },
    // 修改按钮
    async handleEdit(index, row) {
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      this.title = '修改费率'
      await api.getDataById(row.id).then(res => {
        if (res.status == '200') {
          this.innerForm = res.data.data
          console.log(this.innerForm);
          this.innerForm.cargoCategoryCode = this.innerForm.cargoCategoryCode.split(',')
        }
      })
    },
    /**
         * 新建、编辑保存
         */
    submitInner() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.innerForm.cargoCategoryName = []
          this.innerForm.cargoCategoryCode.forEach(item => {
            this.innerForm.cargoCategoryName.push(this.cargoList.filter(i => i.cargoCategoryCode == item)[0].cargoCategoryName)
          })
          const form = JSON.parse(JSON.stringify(this.innerForm))
          form.cargoCategoryName = form.cargoCategoryName.join()
          form.cargoCategoryCode = form.cargoCategoryCode.join()
          if (this.title == '新建费率') {
            api.addData(form).then(res => {
              if (res.status == '200') {
                this.getData()
                this.drawerInner = false
                this.$message.success(res.data.msg)
              }
            })
          } else {
            const updateForm = {
              id: form.id,
              companyId: form.companyId,
              companyName: form.companyName,
              equipmentTypeId: form.equipmentTypeId,
              equipmentTypeName: form.equipmentTypeName,
              cooperationId: form.cooperationId,
              cooperationName: form.cooperationName,
              cargoCategoryCode: form.cargoCategoryCode,
              cargoCategoryName: form.cargoCategoryName,
              position: form.position,
              tradeType: form.tradeType,
              processCode: form.processCode,
              processName: form.processName,
              processCodeItem: form.processCodeItem,
              processNameItem: form.processNameItem,
              startRegionCode: form.startRegionCode,
              startRegionName: form.startRegionName,
              endRegionCode: form.endRegionCode,
              endRegionName: form.endRegionName,
              unitCode: form.unitCode,
              unitName: form.unitName,
              rate: form.rate,
              rateType: '1',
              isOil: form.isOil,
              remark: form.remark
            }
            api.updateData(updateForm).then(res => {
              if (res.status == '200') {
                this.getData()
                this.drawerInner = false
                this.$message.success(res.data.msg)
              }
            })
          }
        }
      })
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.getData()
    },
    async handleDelete(val, id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteData(id).then(res => {
          if (res.data.code === '0000') {
            this.getData()

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getData()
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.drawerOut) {
        oldV = this.oldOut
        newV = this.outForm
      }
      if (this.drawerInner) {
        oldV = this.oldInner
        newV = this.innerForm
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.selectBox {
    justify-content: space-between;
    display: flex;
    background: #ffffff;
    border: 1px solid #e1e4eb;
    border-bottom: 0;
    border-left: none;
    height: 50px;
    position: relative;
    align-items: center;
    padding-left: 14px;
    padding-right: 20px;
}

.input_box {
    display: flex;
}

.page {
    background: #ffffff;
    text-align: right;
    border-radius: 0 0 4px 4px;
    padding: 5px 20px;
}

/deep/.el-tabs--border-card>.el-tabs__content {
    padding: 0 !important;
}

/deep/ .el-drawer__header {
    margin-bottom: 0;
    padding: 16px;
    border-bottom: 1px solid gainsboro;
}

//抽屉底部样式

.demo-drawer__footer {
    text-align: right;
    padding-right: 20px;
    border-top: 1px solid #c8cfde;
    background-color: #f5f7fa;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    line-height: 50px;
}

.box {
    background: #ffffff;
    border: 1px solid #e1e4eb;
    border-radius: 4px 4px 0 0;
    border-top: none;
}

/deep/.el-drawer__body {
    margin-bottom: 30px;
}
</style>
